const {ccclass, property} = cc._decorator;

@ccclass
export default class Socket extends cc.Component {

   @property
    group: string = 'phone';

    ws:any;

    // onLoad () {}

    start () {

        this.sendWebSocket();

    }

    sendWebSocket() {

        let self = this;
        
        this.ws = new WebSocket("ws://120.25.74.1:10500");

        let login_data = JSON.stringify({"action":"login","app_name":"Socket","app_id":105,"fromid":this.makeString(6),'group':this.group});

        this.ws.onopen = function (event) {
            self.ws.send(login_data);
            console.log("websocket握手成功，发送登录数据:" +login_data);
        };
        this.ws.onmessage = function (event) {
            console.log("response text msg: " + event.data);
        };
        this.ws.onerror = function (event) {
            console.log("Send Text fired an error");
        };
        this.ws.onclose = function (event) {
            console.log("WebSocket instance closed.");
        };

        setTimeout(function () {
            if (self.ws.readyState === WebSocket.OPEN) {
                self.ws.send("Hello WebSocket, I'm a text message");
            } else {
                console.log(login_data);
            }
        }, 3);

    }

    /**
     * wensocket 发送数据给分组客户端
     * @param data object
     * @param group string
     */
    sendMessageToGroup(data,group){
        let self = this;
        let list = JSON.stringify({"action":"to_group", "data":data, 'group': group});
        self.ws.send(list);
        console.log('websocket发送数据'+list);
    }

    /**
     * wensocket 发送数据给指定客户端
     * @param data 
     * @param to_id 
     */
    sendMessageToId(data,to_id){
        let self = this;
        let list = JSON.stringify({"action":"to_single", "data":data, 'toid': to_id});
        self.ws.send(list);
        console.log('websocket发送数据'+list);
    }

    makeString(number:number = 6): string {
        let outString: string = '';
        let inOptions: string = 'abcdefghijklmnopqrstuvwxyz0123456789';
    
        for (let i = 0; i < number; i++) {
    
          outString += inOptions.charAt(Math.floor(Math.random() * inOptions.length));
    
        }
    
        return outString;

      }

    // update (dt) {}
}
